//-------------------------------------------------------------------------
// Copyright (c) 2000-2009 Ufinity. All Rights Reserved.
//
// This software is the confidential and proprietary information of
// Ufinity
//
// Original author: zzz
//
//-------------------------------------------------------------------------
// UFINITY MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
// THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UFINITY SHALL NOT BE
// LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
// MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
//
// THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
// CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
// PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
// NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
// SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
// SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
// PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). UFINITY
// SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
// HIGH RISK ACTIVITIES.
//-------------------------------------------------------------------------

package org.ufinity.hsms.module.login.activity;

import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import org.ufinity.hsms.R;
import org.ufinity.hsms.common.activity.BaseActivity;
import org.ufinity.hsms.common.application.HSMApplication;
import org.ufinity.hsms.common.command.AbstractCommand;
import org.ufinity.hsms.common.command.CommandService;
import org.ufinity.hsms.common.command.ICallBack;
import org.ufinity.hsms.common.utils.InfoHelper;
import org.ufinity.hsms.common.utils.StringUtils;
import org.ufinity.hsms.common.utils.ZabbixApiClient;
import org.ufinity.hsms.module.MainActivity;
import org.ufinity.hsms.module.TabbarActivity;
import org.ufinity.hsms.module.login.command.LoginCommand;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import static org.ufinity.hsms.common.tool.logs.Logs.d;

public class LoginActivity extends BaseActivity implements OnClickListener{
	private static final String TAG = "LoginActivity";
	Button btn_Login;
	EditText edt_user_name, edt_password;
	Animation animation;
	CheckBox remember_password;
	ProgressDialog proDialog = null;
	HSMApplication application;
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
	    super.onCreate(savedInstanceState);
	    requestWindowFeature(Window.FEATURE_NO_TITLE); //声明使用自定义标题     
	    setContentView(R.layout.login);
	    instance = this;
	    application = this.getBaseApplication();
		application.addActivity(this);
		
	    btn_Login = (Button)this.findViewById(R.id.btn_login);
	    btn_Login.setOnClickListener(this);
	    remember_password = (CheckBox)this.findViewById(R.id.cb_password);
	    remember_password.setOnClickListener(this);
	    edt_user_name = (EditText)this.findViewById(R.id.edt_user_name);
	    edt_password = (EditText)this.findViewById(R.id.edt_password);
	    animation = AnimationUtils.loadAnimation(this, R.anim.shake);
	    initControls();
	}
	
	
	private void initControls()
	{
		SharedPreferences sharedPreferences = this.getSharedPreferences("remember", Activity.MODE_PRIVATE);
		boolean isChecked = sharedPreferences.getBoolean("ischecked", false);
		String username = sharedPreferences.getString("username", "");
		String password = sharedPreferences.getString("password", "");
		remember_password.setChecked(isChecked);
		if (isChecked){
			edt_user_name.setText(username);
	    	edt_password.setText(password);
		}
		
		proDialog = new ProgressDialog(instance);
		proDialog.setMessage(getResources().getString(R.string.getting_date));
		proDialog.setIndeterminate(false);
		proDialog.setCancelable(true);
	}
	
	/**
	 * 记住密码
	 */
	private void RememberPassword()
	{
		boolean isChecked = false;
		if (remember_password.isChecked()) {
			isChecked = true;
		} else {
			isChecked = false;
		}
		SharedPreferences sharedPreference = this.getSharedPreferences("remember", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreference.edit();
		editor.putBoolean("ischecked", isChecked);
		editor.commit();
	}
	
	
	/**
	 * 登录
	 */
	private void login()
	{
		if (checkFields())
	    {
			final String username = edt_user_name.getText().toString().trim();
			final String password = edt_password.getText().toString().trim();
			SharedPreferences sharedPreference = instance.getSharedPreferences("remember", Activity.MODE_PRIVATE);
			if(sharedPreference.getBoolean("ischecked", false)){
				SharedPreferences.Editor editor = sharedPreference.edit();
    			editor.putString("username", username);
    			editor.putString("password", password);
    			editor.commit();
			}
			if (!InfoHelper.checkNetWork(mContext)) {
				makeMyToast(mContext, getResources().getString(
						R.string.connect_error));
				return;
			}else{
				proDialog.show();
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("password", password);
				map.put("user", username);
				LoginCommand cmd = new LoginCommand(map);
				cmd.addCallBack("login",new ICallBack<JSONObject>() {
					
					@Override
					public void callBack(AbstractCommand<JSONObject> command,
							JSONObject json, Exception ex) {
						//{"jsonrpc":"2.0","result":"64511f847fceb55cd20e07404119448e","id":"2"}
						if (json!=null && !json.isNull("result"))
						{
							String result;
							try {
								result = json.getString("result");
								ZabbixApiClient.SessionId = result;
				    			StartMonitorService();
				    			Intent intent = new Intent(instance, TabbarActivity.class);
				    			startActivity(intent);
				    			finish();
				    			
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}else{
							//d(TAG,json.toString());
							makeMyToast(instance, getResources().getString(R.string.time_out));
						}
						if(proDialog!=null){
							proDialog.dismiss();
						}
					}
				});
				CommandService.addTaskAtFirst(cmd);
				
		    }
		}
	}

	
	/*
	 * 检查输入字段的值
	 * 
	*/
	private boolean checkFields()
	{
		String username = edt_user_name.getText().toString().trim();
		String pwd = edt_password.getText().toString().trim();
		if (StringUtils.isBlank(username)){
			edt_user_name.startAnimation(animation);
			return false;
		}
		
		if (StringUtils.isBlank(pwd)){
			edt_password.startAnimation(animation);
			return false;
		}
		return true;
	}
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK){
			finish();
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	private void StartMonitorService()
	{
		/*Intent serviceIntent = new Intent(this, ServerMonitorService.class);
		startService(serviceIntent);*/
	}
	
	private void StopMonitorService()
	{
		/*Intent serviceIntent = new Intent(this, ServerMonitorService.class);
		stopService(serviceIntent);*/
	}


	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
	    	case R.id.btn_login:
	    		login();
	    		break;
	    	case R.id.cb_password:
	    		RememberPassword();
	    		break;
		}
	}
}